import axios from 'axios';
import { Toast } from 'antd-mobile';

const instance = axios.create({
    baseURL: '/api', // 和PC端保持一致
    timeout: 10000,
});

instance.interceptors.request.use(config => {
    const token = localStorage.getItem('accessToken');
    if (token) config.headers.Authorization = `Bearer ${token}`;
    return config;
});

let isRefreshing = false;
let refreshSubscribers: Array<(token: string) => void> = [];

function onRefreshed(token: string) {
    refreshSubscribers.forEach(cb => cb(token));
    refreshSubscribers = [];
}

function addRefreshSubscriber(cb: (token: string) => void) {
    refreshSubscribers.push(cb);
}

// 响应拦截器
instance.interceptors.response.use(
    response => {
        if (response.data.code && response.data.code !== 200) {
            Toast.show({ icon: 'fail', content: response.data.msg || '系统错误' });
        }
        return response;
    },
    async error => {
        const originalRequest = error.config;
        if (error.response && error.response.status === 401) {
            const refreshToken = localStorage.getItem('refreshToken');
            if (refreshToken && !originalRequest._retry) {
                if (isRefreshing) {
                    // 正在刷新token，队列等待
                    return new Promise(resolve => {
                        addRefreshSubscriber((token: string) => {
                            originalRequest.headers.Authorization = `Bearer ${token}`;
                            resolve(instance(originalRequest));
                        });
                    });
                }
                originalRequest._retry = true;
                isRefreshing = true;
                try {
                    const res = await axios.post('/api/refreshToken', { refreshToken });
                    if (res.data.code === 200) {
                        const { accessToken, refreshToken: newRefreshToken } = res.data.data;
                        localStorage.setItem('accessToken', accessToken);
                        localStorage.setItem('refreshToken', newRefreshToken);
                        instance.defaults.headers.Authorization = `Bearer ${accessToken}`;
                        onRefreshed(accessToken);
                        // 重试原请求
                        originalRequest.headers.Authorization = `Bearer ${accessToken}`;
                        return instance(originalRequest);
                    } else {
                        localStorage.removeItem('accessToken');
                        localStorage.removeItem('refreshToken');
                        window.location.href = '/login';
                        return Promise.reject(error);
                    }
                } catch (e) {
                    localStorage.removeItem('accessToken');
                    localStorage.removeItem('refreshToken');
                    window.location.href = '/login';
                    return Promise.reject(error);
                } finally {
                    isRefreshing = false;
                }
            } else {
                localStorage.removeItem('accessToken');
                localStorage.removeItem('refreshToken');
                window.location.href = '/login';
            }
        } else {
            Toast.show({ icon: 'fail', content: '网络错误或系统异常' });
        }
        return Promise.reject(error);
    }
);

// 获取虚拟账户信息
export function getAccountInfo() {
    return instance.post('/virtualAccount/queryAccount', {});
}

// 获取虚拟账户交易记录
export function getAccountTransactions(params: { userId: string; current?: number; pageSize?: number }) {
    return instance.post('/withdrawRecord', params);
}

// 发起充值
export function rechargeAccount(params: { bankId: number; amount: number; remark?: string }) {
    return instance.post('/virtualAccount/recharge', params);
}

// 发起提现
export function withdrawAccount(params: { bankId: number; amount: number; remark?: string }) {
    return instance.post('/virtualAccount/withdraw', params);
}

// 发起转账
export function transferAccount(params: { toAccountNo: string; amount: number; remark?: string }) {
    return instance.post('/virtualAccount/transfer', params);
}

export default instance;
